<template>
  <div class="area-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>区域管理</h2>
      <p>管理系统中的多级区域信息</p>
    </div>

    <!-- 搜索表单 -->
    <SearchForm
      v-model="searchParams"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="区域名称">
        <el-input
          v-model="searchParams.name"
          placeholder="请输入区域名称"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="区域编码">
        <el-input
          v-model="searchParams.code"
          placeholder="请输入区域编码"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="区域级别">
        <el-select
          v-model="searchParams.level"
          placeholder="请选择区域级别"
          clearable
        >
          <el-option label="省/直辖市" :value="1" />
          <el-option label="市/区" :value="2" />
          <el-option label="县/区" :value="3" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态">
        <el-select
          v-model="searchParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </SearchForm>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增区域
      </el-button>
      <el-button @click="expandAll">
        <el-icon><Expand /></el-icon>
        展开全部
      </el-button>
      <el-button @click="collapseAll">
        <el-icon><Fold /></el-icon>
        收起全部
      </el-button>
      <el-button @click="loadAreaList" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>

    <!-- 区域树形表格 -->
    <el-table
      ref="tableRef"
      :data="filteredAreaList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :default-expand-all="false"
      v-loading="loading"
    >
      <el-table-column prop="name" label="区域名称" min-width="200">
        <template #default="{ row }">
          <div class="area-name">
            <el-icon v-if="row.level === 1" class="level-icon province"><Location /></el-icon>
            <el-icon v-else-if="row.level === 2" class="level-icon city"><OfficeBuilding /></el-icon>
            <el-icon v-else-if="row.level === 3" class="level-icon district"><MapLocation /></el-icon>
            <span>{{ row.name }}</span>
          </div>
        </template>
      </el-table-column>
      
      <el-table-column prop="code" label="区域编码" width="120" />
      
      <el-table-column prop="level" label="级别" width="80">
        <template #default="{ row }">
          <el-tag :type="getLevelTagType(row.level)">
            {{ getLevelText(row.level) }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column prop="parentName" label="上级区域" width="150" />
      
      <el-table-column prop="sort" label="排序" width="80" />
      
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      
      <el-table-column prop="createTime" label="创建时间" width="160" />
      
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleAdd(row)"
            v-if="row.level < 3"
          >
            添加下级
          </el-button>
          <el-button
            type="primary"
            size="small"
            link
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            link
            @click="handleDelete(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="上级区域" prop="parentId" v-if="formData.parentId">
          <el-input v-model="parentAreaName" disabled />
        </el-form-item>
        
        <el-form-item label="区域名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入区域名称" />
        </el-form-item>
        
        <el-form-item label="区域编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入区域编码" />
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import {
  Plus,
  Expand,
  Fold,
  Location,
  OfficeBuilding,
  MapLocation,
  Refresh
} from '@element-plus/icons-vue'
import SearchForm from '@/components/SearchForm.vue'
import { areaApi } from '@/api/area'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const tableRef = ref<InstanceType<typeof ElTable>>()
const formRef = ref()

// 区域列表数据
const areaList = ref<any[]>([])
const searchParams = reactive({
  name: '',
  code: '',
  level: '',
  status: ''
})

// 表单数据
const formData = reactive({
  id: undefined as number | undefined,
  parentId: undefined as number | undefined,
  name: '',
  code: '',
  level: 1,
  sort: 0,
  status: 1,
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入区域名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入区域编码', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return formData.id ? '编辑区域' : '新增区域'
})

const parentAreaName = computed(() => {
  if (!formData.parentId) return ''
  const parent = findAreaById(areaList.value, formData.parentId)
  return parent ? parent.name : ''
})

const filteredAreaList = computed(() => {
  if (!searchParams.name && !searchParams.code && !searchParams.level && searchParams.status === '') {
    return areaList.value
  }
  return filterAreas(areaList.value, searchParams)
})

// 方法
const loadAreaList = async () => {
  try {
    loading.value = true
    const response = await areaApi.getAreaTree()
    areaList.value = response.data
  } catch (error) {
    ElMessage.error('加载区域列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  // 搜索时重新加载数据
  console.log('搜索参数:', searchParams)
  loadAreaList()
}

const handleReset = () => {
  Object.assign(searchParams, {
    name: '',
    code: '',
    level: '',
    status: ''
  })
  console.log('重置搜索条件')
  loadAreaList()
}

const handleAdd = (parent?: any) => {
  resetForm()
  if (parent) {
    formData.parentId = parent.id
    formData.level = parent.level + 1
  } else {
    formData.level = 1
  }
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  Object.assign(formData, {
    id: row.id,
    parentId: row.parentId,
    name: row.name,
    code: row.code,
    level: row.level,
    sort: row.sort,
    status: row.status,
    remark: row.remark
  })
  dialogVisible.value = true
}

const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除区域"${row.name}"吗？删除后不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await areaApi.deleteArea(row.id)
    ElMessage.success('删除成功')
    loadAreaList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleStatusChange = async (row: any) => {
  try {
    await areaApi.updateAreaStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    ElMessage.error('状态更新失败')
    row.status = row.status === 1 ? 0 : 1 // 回滚状态
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    submitting.value = true
    
    if (formData.id) {
      await areaApi.updateArea(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      await areaApi.createArea(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadAreaList()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    parentId: undefined,
    name: '',
    code: '',
    level: 1,
    sort: 0,
    status: 1,
    remark: ''
  })
  formRef.value?.resetFields()
}

const expandAll = () => {
  const expandAllRows = (data: any[]) => {
    data.forEach(row => {
      tableRef.value?.toggleRowExpansion(row, true)
      if (row.children?.length) {
        expandAllRows(row.children)
      }
    })
  }
  expandAllRows(areaList.value)
}

const collapseAll = () => {
  const collapseAllRows = (data: any[]) => {
    data.forEach(row => {
      tableRef.value?.toggleRowExpansion(row, false)
      if (row.children?.length) {
        collapseAllRows(row.children)
      }
    })
  }
  collapseAllRows(areaList.value)
}

const getLevelTagType = (level: number) => {
  const types = ['', 'success', 'warning', 'info']
  return types[level] || 'info'
}

const getLevelText = (level: number) => {
  const texts = ['', '省/市', '市/区', '县/区']
  return texts[level] || '未知'
}

const findAreaById = (areas: any[], id: number): any => {
  for (const area of areas) {
    if (area.id === id) return area
    if (area.children?.length) {
      const found = findAreaById(area.children, id)
      if (found) return found
    }
  }
  return null
}

const filterAreas = (areas: any[], params: any): any[] => {
  return areas.filter(area => {
    let match = true
    
    if (params.name && !area.name.includes(params.name)) {
      match = false
    }
    if (params.code && !area.code.includes(params.code)) {
      match = false
    }
    if (params.level && area.level !== params.level) {
      match = false
    }
    if (params.status !== '' && area.status !== params.status) {
      match = false
    }
    
    if (match) return true
    
    // 检查子级是否匹配
    if (area.children?.length) {
      const filteredChildren = filterAreas(area.children, params)
      if (filteredChildren.length > 0) {
        area.children = filteredChildren
        return true
      }
    }
    
    return false
  })
}

// 生命周期
onMounted(() => {
  loadAreaList()
})
</script>

<style lang="scss" scoped>
.area-list {
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
    }
    
    p {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }
  
  .action-bar {
    margin: 16px 0;
    display: flex;
    gap: 12px;
  }
  
  .area-name {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .level-icon {
      font-size: 16px;
      
      &.province {
        color: #67c23a;
      }
      
      &.city {
        color: #409eff;
      }
      
      &.district {
        color: #e6a23c;
      }
    }
  }
}
</style>